package com.httpClient.chapter2;

import com.JavaNet.chapter8_client_socket.SocketForHttp;
import com.httpClient.chapter2.config.OAConfig;
import com.httpClient.util.ResponseUtil;
import com.sky.JULLog.MyJulLogger;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

/**
 * 对比 {@link  SocketForHttp }  ,
 *
 * @author : wushikai
 * date : 2024-06-17
 */
public class MultiPartForm {
    private static Logger log = MyJulLogger.getLogger(MultiPartForm.class);
    private static File TEST_FILE = new File(ClassLoader.getSystemClassLoader().getResource("JUL.properties").getFile());

    static {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");   //这样会输出代理class文件

    }

    @Test
    public void doPost() {
        HttpClient httpclient = HttpClients.createDefault();
        /*-----------------   mark 组装一个 post  multipart  请求体   -------------*/
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setContentType(ContentType.MULTIPART_FORM_DATA);  //设置头为 multipart/form-data
        multipartEntityBuilder.setCharset(StandardCharsets.UTF_8);
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //mark  设置浏览器兼容模式?
        multipartEntityBuilder.addPart("file", new FileBody(TEST_FILE))
                .addPart(FormBodyPartBuilder.create(
                        "sp.lk.merchant_name",
                        new StringBody("广西", ContentType.create("text/plain", Consts.UTF_8))
                ).build());

        HttpEntity multipartEntity = multipartEntityBuilder.build();
        /*-----------------                                  -------------*/

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)    //和服务器的连接超时时间
                .setSocketTimeout(10*1000)   //和服务器交互数据的超时时间
                .setConnectionRequestTimeout(1000)  //从连接池获取 空闲请求的超时时间
                .build();

        /*-----------------           -------------*/
        try {
            URI uri = new URI(OAConfig.SCHEMA, "", OAConfig.HOST, OAConfig.PORT, "/", null , null );
            HttpPost httpPost = new HttpPost(uri);
            //mark update  Content-Type ,  因为boundary 都是en 所以没有必要添加 charset ;
            httpPost.addHeader("Content-Type", "multipart/form-data;");
            httpPost.addHeader("accessToken" , "sky1234");
            httpPost.setEntity(multipartEntity);
            httpPost.setConfig(  requestConfig   );
            System.out.println("httpPost.getRequestLine().toString() = " + httpPost.getRequestLine().toString());
            httpPost.setHeader(new Header() {
                @Override
                public HeaderElement[] getElements() throws ParseException {
                    return new HeaderElement[0];
                }
                @Override
                public String getName() {
                    return "Content-Type";
                }
                @Override
                public String getValue() {
                    String value = multipartEntity.getContentType().getValue();
                    if (value.contains("charset")) {
                        value = value.substring(0, value.lastIndexOf("charset"));
                        value = value.substring(0, value.lastIndexOf(";"));
                    }
                    log.info("value=" + value);
                    return value;
                }
            });
            HttpResponse response = httpclient.execute(httpPost);  //使用 httpClient 调用 get请求
            ResponseUtil.handleResponse(response);
        } catch (URISyntaxException synE) {
            log.severe(synE.getMessage());  synE.printStackTrace();
        } catch (IOException ioe) {
            log.severe(ioe.getMessage());  ioe.printStackTrace();
        }
    }


}



